package com.sgxy.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sgxy.entity.DocumentInf;
import com.sgxy.entity.UserInf;
import com.sgxy.service.DocumentInfService;
import com.sgxy.service.UserInfService;
//import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.net.URLEncoder;

@Controller
@RequestMapping("/document")
public class DocumentInfController {
    private final DocumentInfService documentInfService;
//    private   UserInfService userInfService;
    @Autowired
    public DocumentInfController(DocumentInfService documentInfService) {
        this.documentInfService = documentInfService;
    }

//从这里---------全是用来测试的，并没有什么用处
//    @RequestMapping("/toshowUpdateDocument")
//    public ModelAndView toIndex(int id) {
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("documentId",id);
//        modelAndView.setViewName("document/showUpdateDocument.jsp");
//        return modelAndView;
//    }
//    @RequestMapping("/toAddcontroller")
//    public ModelAndView toADD(){
//        ModelAndView modelAndView = new ModelAndView();
//
//
//        modelAndView.setViewName("document/upload.jsp");
//        return modelAndView;
//    }
//
//    @RequestMapping("/toshowAddDocument")
//    public String toIndex() {
//
//        return "redirect:/showAddDocument";
//    }
//到这里---------全是用来测试的，并没有什么用处




    //分页查询
    @RequestMapping("/selectdocument")
    public ModelAndView selectEmployeeAction(
                                             @RequestParam(value = "page", defaultValue = "1")Integer page
                                                       ,DocumentInf documentInf ){
        ModelAndView modelAndView = new ModelAndView();
        PageHelper.startPage(page,10);
        List<DocumentInf> documentInfs = documentInfService.QueryDocumentInfs(documentInf);
        PageInfo<DocumentInf> documentInfPageInfo = new PageInfo<>(documentInfs);
        //这个是查询到的document指塞进model
//        modelAndView.addObject("documentInf", documentInfs);
        //这个是封装成分页插件格式到的document指塞进model
        modelAndView.addObject("documentInfPageInfo",documentInfPageInfo);
        modelAndView.addObject("documentInf",documentInf);
        modelAndView.setViewName("/document/document.jsp");
        return modelAndView;
    }

/*
* 此处是文件上传模块
* 需要三个参数
*
* MultipartFile这个是在form表单中添加enctype="multipart/form-data"
* 就提交表单后就可以获取 <input type="file" name="some"   size="30"/>
*中的MultipartFile元素了，通过name来获取。
* 最终调用uploadFile(some);完成文件进入电脑的"D:/test1/"
*
* userId是登录那个用户的，用来加入数据库是谁上传的，按道理是可以拿你登录后main的那个来获取，但是我拿不到
*
*此处的title remark等是表单内的属性，我不知道怎么前端打包成document的entity传来
* */

    @RequestMapping("/toAdddocument")
    public ModelAndView toAdddocumentAction(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/document/showAddDocument.jsp");
        return modelAndView;
    }

    @RequestMapping("/adddocument")
    public ModelAndView addDocumentAction(DocumentInf documentInf,MultipartFile some){

        ModelAndView modelAndView  = new ModelAndView();
//        System.out.println("jinlaile");
//        uploadFile(some);
//        UserInf userInf=new UserInf();
//        DocumentInf documentInf=new DocumentInf();
//        userInf=userInfService.queryUserInf(userId);

        String filename=uploadFile(some);
        documentInf.setFilename(filename);
        documentInfService.AddDocumentInf(documentInf);
//        System.out.println("chenggongle");

            //modelAndView.setViewName("main.jsp");
        modelAndView.setViewName("redirect:/document/toAdddocument");
        return modelAndView;
    }
    /*
    * 修改文件信息
    * */
    @RequestMapping("/toUpdatedocument")
    public ModelAndView toupdatedocumentAction(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        DocumentInf documentInf = documentInfService.QueryDocumentInf(id);
        modelAndView.addObject("documentInf",documentInf);
        modelAndView.setViewName("/document/showUpdateDocument.jsp");
        return modelAndView;
    }

    @RequestMapping("/updatedocument")
    public ModelAndView updateDocumentInfAction(DocumentInf documentInf,MultipartFile some){

        ModelAndView modelAndView = new ModelAndView();
        if(some!=null){
            String filename=uploadFile(some);
            documentInf.setFilename(filename);
        }
        documentInfService.UpdateDocumentInf(documentInf);
        modelAndView.setViewName("redirect:/document/selectdocument");
        return modelAndView;
    }

//    @RequestMapping("/toDownload")
//    public ModelAndView toDownloadAction(Integer id, HttpServletResponse response) throws IOException {
//        ModelAndView modelAndView = new ModelAndView();
//        DocumentInf documentInf = documentInfService.QueryDocumentInf(id);
//        String name = documentInf.getFilename();
//        downloadFile(name,response);
////        modelAndView.addObject("info_download","下载成功！");
//        modelAndView.setViewName("redirect:/document/selectdocument");
//        return modelAndView;
//    }

    @RequestMapping("/deletedocument")
    public ModelAndView deleteDocumentAction(String ids){
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(ids);
        String[] split = ids.split(",");
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0;i<split.length;i++){
            list.add(Integer.valueOf(split[i]));
        }
        System.out.println(ids);
        documentInfService.DeleteDocumentInf(list);
        modelAndView.setViewName("redirect:/document/selectdocument");
        return modelAndView;
    }

    public String uploadFile(MultipartFile some){
        //获取上传文件名
        String filename = some.getOriginalFilename();
        //此处为路径1系统自动生成在项目中的文件夹document中,sout方法查看位置，此处我设置为绝对路径
        //String path = session.getServletContext().getRealPath("/document");
        //System.out.println(path);
        String path = "D:/test1/";
//文件信息存进数据库
//        DocumentInf documentInf =new DocumentInf();
//        documentInf.setTitle(name);
//        documentInf.setFilename(filename);
//        documentInfService.AddDocumentInf(documentInf);
        //文件上传
        File file = new File(path, filename);
//        if (!file.exists()) {
//            file.mkdir();
//        }
        try {
            some.transferTo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filename;
    }

    @RequestMapping("/download")
    private void downloadFile(Integer id ,HttpServletResponse response) throws IOException {
        //ModelAndView modelAndView = new ModelAndView();
        //此次自动获取系统自动生成的文件路径在、document下，但是我设置成绝对路径了
        //String path = request.getServletContext().getRealPath("/document");
        DocumentInf documentInf = documentInfService.QueryDocumentInf(id);
        String name = documentInf.getFilename();
        String path = "D:/test1/";
        File file = new File(path);
        //输出流
        InputStream in=new FileInputStream(new File(path,name));
        //响应头
        response.addHeader("Content-Type","application/octet-stream");
        //设置下载方是以附件形式来下载 不要解析，和设置文件名
        response.addHeader("Content-Disposition", "attachment;filename="+
                URLEncoder.encode(name,"UTF-8"));
        OutputStream out=response.getOutputStream();
//        流复制
        byte[] buffer=new byte[1024];
        int len=-1;
        while ((len=in.read(buffer))!=-1){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
        //modelAndView.setViewName("main.jsp");

        //return modelAndView;

    }
}
